package com.kefu.admin.common.zk;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by TWD on 2018/7/27.
 */
public class ZkClientCreator {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZkClientCreator.class);

    private static final int SESSION_TIMEOUT = 60000;
    private static final int CONNECTION_TIMEOUT = 10000;
    private static final String ZkAddress="127.0.0.1:2181";

    private static class SingletonHolder{
        //public static ZkClient zkClient = new ZkClient(ZkAddress, SESSION_TIMEOUT, CONNECTION_TIMEOUT, new BytesPushThroughSerializer());
        public static ZkClient zkClient = new ZkClient(ZkAddress, SESSION_TIMEOUT, CONNECTION_TIMEOUT);
    }
    public static ZkClient getZkClient(){
        //这种从jvm虚拟机上保证了单例，并且也是懒式加载。
        return SingletonHolder.zkClient;
    }

    public static void createPersistentNode(ZkClient client, String path) {
        boolean exist = getZkClient().exists(path);
        if (!exist) {
            LOGGER.info("ZkClientCreator|createPersistentNode|Create node:【{}】" , path);
            // 递归创建节点
            client.createPersistent(path, true);
        }
    }
}
